package com.lhq.tag_tales.schedule.recommendUsers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhq.tag_tales.common.ErrorCodeEnum;
import com.lhq.tag_tales.exception.BusinessException;
import com.lhq.tag_tales.model.domain.User;
import com.lhq.tag_tales.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.lhq.tag_tales.constant.RedisConstant.*;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.MINUTES;

/**
 * 预热推荐用户
 */
@Slf4j
public class RecommendUsersJob extends QuartzJobBean {
    private static final long CURRENT_PAGE=1;
    private static final long PAGE_SIZE=20;
    //重点用户
    private final List<Long> hotUsers= Arrays.asList(1L,2L,3L);
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private RedissonClient redissonClient;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        RLock lock = redissonClient.getLock(RECOMMEND_USER_LOCK);
        try {
            //参数讲解：锁的等待时间，锁的过期时间，锁的时间单位
            if (lock.tryLock(0, 1, DAYS)) {
                log.info("获取锁成功,进程ID:{}",Thread.currentThread().getId());
                //从数据库中加载出所有的用户数据
                QueryWrapper<User> queryWrapper=new QueryWrapper<>();
                //封装成Page对象
                Page<User> userPage=userService.page(new Page<>(CURRENT_PAGE,PAGE_SIZE),queryWrapper);
                if (userPage == null){
                    throw new BusinessException(ErrorCodeEnum.DEFAULT_ERROR);
                }
                userPage.setRecords(userPage.getRecords().stream()
                        .map(user->userService.getSafetyUser(user))
                        .collect(Collectors.toList()));
                //缓存到redis中
                String key;
                for (Long userId : hotUsers) {
                    key=RECOMMEND_USER_PREFIX+userId;
                    try {
                        log.info("缓存预热用户："+key);
                        redisTemplate.opsForValue().set(key,userPage,RECOMMEND_USER_TO,MINUTES);
                    } catch (Exception e) {
                        log.error("redis操作异常",e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("获取锁失败",e);
        }finally {
            //确保释放的是本线程才释放
            if (lock.isHeldByCurrentThread()) {
                log.info("释放锁成功,进程ID:{}",Thread.currentThread().getId());
                //确保锁释放
                lock.unlock();
            }
        }
    }
}
